﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using OnlineVideos.Library;
//using OnlineVideos.ViewModels;
using System.Text.RegularExpressions;
using Common.Library;
using OnlineVideos.Data;
using Common.Utilities;
using OnlineVideos.Common;
using System.IO;
using System.IO.IsolatedStorage;
using AdRotator;
using System.Threading.Tasks;
using OnlineVideos.Entities;

namespace OnlineVideos.Views
{
    public partial class BrowserPage : PhoneApplicationPage
    {
        Stack<Uri> history = new Stack<Uri>();
        Uri current = null;
       
        string ssss = string.Empty;
        List<AutoComplete> v = new List<AutoComplete>();

        public string navigatingURL;
        public string loadedURL;
        public BrowserPage()
        {
            InitializeComponent();
            this.Loaded += BrowserPage_Loaded;
            this.OrientationChanged += new EventHandler<OrientationChangedEventArgs>(BrowserPage_OrientationChanged);
            
        }

        void BrowserPage_Loaded(object sender, RoutedEventArgs e)
        {
            Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
            AdRotatorControl Adc = frameBorder.FindName("AdRotatorWin8") as AdRotatorControl;
            Adc.IsAdRotatorEnabled = false;
            Adc.Visibility = Visibility.Collapsed;
        }

       
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);


            if (history.Count > 0)
            {
                Uri destination = history.Peek();
                webBrowser1.Navigate(destination);
                // What about using script and going history.back? 
                // you can do it, but 
                // I rather use that to keep ‘track’ consistently with our stack 
                e.Cancel = true;

            }
            else
            {

            }
        }

        void BrowserPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            try
            {
                if (e.Orientation == PageOrientation.Portrait || e.Orientation == PageOrientation.PortraitDown || e.Orientation == PageOrientation.PortraitUp)
                {
                    webBrowser1.Height = 740;
                    webBrowser1.Width = 480;
                    txtlink.Width = 410;
                    txtlink.Margin = new Thickness(0, -5, 0, 0);
                    imgfldr.Width = 90;
                    imgfldr.Margin = new Thickness(0, -4, 0, 0);
                    //Grid.SetRow(buttonList, 0);

                }
                else
                {
                    webBrowser1.Height = 420;
                    webBrowser1.Width = 800;
                    //Grid.SetRow(buttonList, 1);
                    txtlink.Margin = new Thickness(0, -5, 0, 0);
                    txtlink.Width = 730;
                    imgfldr.Margin = new Thickness(-20, -5, 0, 0);
                    imgfldr.Width = 100;

                }

            }


            catch (Exception ex)
            {
                string excepmess = "Exception in BrowserPage_OrientationChanged Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
            }
        }

        public void navigate()
        {

           
            NavigationService.Navigate(new Uri("/ShowList.xaml", UriKind.Relative));
        }
       
       
        private void webBrowser1_Navigating(object sender, NavigatingEventArgs e)
        {
            try
            {
                navigatingURL = e.Uri.ToString();
                txtlink.Text = navigatingURL;
                AppSettings.NavigationUrl = navigatingURL;
               
                if (navigatingURL.Contains(".jpg") || navigatingURL.Contains(".doc") || navigatingURL.Contains(".mp3") || navigatingURL.Contains(".png"))
                {
                    NavigationService.Navigate(new Uri("/Views/Downloding.xaml?url=" + navigatingURL, UriKind.Relative));
                }
            }

            catch (Exception ex)
            {
                string excepmess = "Exception in webBrowser1_Navigating Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
            }
        }



        private void webBrowser1_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                performanceProgressBar.IsIndeterminate = false;
                txtlink.Margin = new Thickness(20, 0, 0, 0);
                txtlink.Width = 400;
                imgfldr.Visibility = Visibility.Visible;
                loadedURL = e.Uri.ToString();
                string htmltext = webBrowser1.SaveToString();
            }


            catch (Exception ex)
            {
                string excepmess = "Exception in webBrowser1_LoadCompleted Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
            }
        }

        private void txtlink_KeyUp(object sender, KeyEventArgs e)
        {
   
            try
            {
                if (txtlink.Text != "")
                {
                    txtmessage.Visibility = Visibility.Collapsed;
                    string url = "";
                    string url1 = "";
                    var hist = Task.Run(async()=> await Constants.connection.Table<BrowserHistory>().ToListAsync()).Result; 
                    if (hist.Count() > 0)
                    {
                        foreach (var gh in hist)
                        {
                            AutoComplete d = new AutoComplete();
                            d.urllist = gh.PreText;
                            v.Add(d);
                        }
                    }
                    txtlink.ItemsSource = v;
                    if (e.Key == Key.Enter)
                    {
                        performanceProgressBar.IsIndeterminate = true;
                        if (txtlink.Text != "")
                        {
                            url = txtlink.Text;
                            if (url.StartsWith("http://www."))
                            {
                                SaveInfo(url);
                                AppSettings.starturidownloadmanger = url;
                                webBrowser1.Navigate(new Uri(url, UriKind.RelativeOrAbsolute));
                            }
                            else
                            {
                                url = url.Substring(url.LastIndexOf('/') + 1);
                                if (url.Contains("channel9.msdn"))
                                {
                                    url1 = "http://" + url;
                                }
                                else
                                {
                                    if (url.Contains("www"))
                                    {
                                        url1 = "http://" + url;
                                    }
                                    else
                                        url1 = "http://www." + url;
                                }
                                SaveInfo(url1);
                                AppSettings.starturidownloadmanger = url1;
                                webBrowser1.Navigate(new Uri(url1, UriKind.RelativeOrAbsolute));
                            }
                        }
                    }
                }
                else
                {
                    txtmessage.Visibility = Visibility.Visible;
                }
            }

            catch (Exception ex)
            {
                string excepmess = "Exception in txtlink_KeyUp Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
            }
        }

        public void SaveInfo(string preurl)
        {
            try
            {
                var his =Task.Run(async()=> await Constants.connection.Table<BrowserHistory>().Where(i=>i.PreText==preurl).ToListAsync()).Result;  
                if (his.Count() > 0)
                {
                }
                else
                {
                    BrowserHistory d = new BrowserHistory()
                    {
                        PreText = preurl
                    };
                    Task.Run(async () => await Constants.connection.InsertAsync(d));
                }
            }
            catch (Exception ex)
            {
                string excepmess = "Exception in SaveInfo Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
            }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            AppSettings.htmltextfordownloadmanger = webBrowser1.SaveToString();

            NavigationService.Navigate(new Uri("/Views/DownloadPivots.xaml", UriKind.Relative));
        }

        private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                Uri previous = null;
                if (history.Count > 0)
                    previous = history.Peek();


                if (e.Uri == previous)
                {
                    history.Pop();
                }
                else
                {
                    if (current != null)
                        history.Push(current);
                }
                current = e.Uri;
            }


            catch (Exception ex)
            {
                string excepmess = "Exception in webBrowser1_Navigated Method In browserpage file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
            }
        }




    }
}